const _ = require('../utils')
const { listParentBehavior, formItemBehavior } = require('../behaviors')

_.create('checkbox-group', {
  properties: {
    label: String,
    value: Array,
    bordered: { type: Boolean, value: false },
    helperText: {
      type: String,
      value: '',
    },
  },

  behaviors: ['wx://form-field', listParentBehavior, formItemBehavior],

  relations: {
    '../checkbox/index': {
      type: 'child',
      linked() {
        this.assignElementSN('../checkbox/index')
      },
      linkChanged() {
        this.assignElementSN('../checkbox/index')
      },
      unlinked() {
        this.assignElementSN('../checkbox/index')
      },
    },

    '../form-validator/index': {
      type: 'ancestor',
    },
  },

  observes: {
    value: function (v) {
      this.updateByValue(v)
    },
  },

  lifetimes: {
    ready() {
      this.updateByValue(this.data.value)
    },
  },

  methods: {
    onChecked() {
      const values = []
      const checkboxes = this.getRelationNodes('../checkbox/index') || []

      checkboxes.forEach((c) => {
        const { checked, value, label } = c.data
        if (checked) values.push(value || label)
      })

      this.setData({ value: values })
      this.triggerEvent(
        'change',
        { value: values },
        {
          bubbles: true,
          composed: true,
        }
      )
    },

    updateByValue(v) {
      const checkboxes = this.getRelationNodes('../checkbox/index') || []

      checkboxes.forEach((c) => c.setChecked(v.indexOf(c.data.value || c.data.label) > -1))
    },
  },
})
